# -*- coding: utf-8 -*-

import configparser

from auto.untils import MySQLDictCursor


def get_conn(database):
    config = configparser.ConfigParser()
    # config_file = get_config_path()
    # if os.path.exists(config_file):
    #     config.read(config_file, encoding='utf-8')
    # else:
    #     print(f"配置文件未找到: {config_file}")
    #     return
    config.read("./config/config.ini", encoding='utf-8')
    db = MySQLDictCursor(
        host=config['database']['host'],
        port=int(config['database']['port']),
        user=config['database']['user'],
        password=config['database']['password'],
        database=database
    )

    return db.get_connection()


def ddl(database, filepath):
    with get_conn(database) as conn:
        # with open("./data/create_database.sql", 'r', encoding='utf-8') as f:
        with open(filepath, 'r', encoding='utf-8') as f:
            sql_content = f.read()

            # 分割成单条 SQL 语句（简单按 ; 分割，注意注释或字符串中的 ; 可能出错）
            # 更健壮的做法是使用 sqlparse 库
            statements = [s.strip() for s in sql_content.split(';') if s.strip()]

            with conn.cursor() as cursor:
                for stmt in statements:
                    if stmt:
                        cursor.execute(stmt)
                conn.commit()
                print("create_database.sql 文件执行成功！")
